package com.chenzhou.product_sys.common;

import com.chenzhou.product_sys.entity.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDAO <T> {

    private Connection conn = null; //数据库连接对象
    private PreparedStatement ps = null; // 执行预编译sql语句对象
    private ResultSet rs = null; //结果集对象
    /***
     * DAO查询方法封装
     * @return
     */
    protected List<T> execute_Query(String sql, Object[] objects){
        conn = DBuitl.get_Connection();
        try {
            ps = conn.prepareStatement(sql);
            setParamater(ps,objects);
            rs = ps.executeQuery();
            return this.resultSetToList(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close_connetion();
        }
        return null;
    }

    protected abstract List<T> resultSetToList(ResultSet rs) throws SQLException;


    /**
     * DAO封装增删改方法
     * @param sql  要求执行的sql语句
     * @param objects  执行sql的参数
     * @return
     */
    protected int execute_modify(String sql,Object[] objects){
        int flag = -1;
        conn = DBuitl.get_Connection();
        try {
            ps = conn.prepareStatement(sql);
            setParamater(ps,objects);
            flag = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close_connetion();
        }
        return flag;
    }

    /**
     * 设置SQL语句参数
     */
    protected void setParamater(PreparedStatement ps,Object[] objects) throws SQLException {
        if(objects!=null) {
            for (int i = 0; i < objects.length; i++) {
                ps.setObject(i + 1, objects[i]);
            }
        }

    }

    /**
     * 关闭数据库连接
     */
    protected void close_connetion(){
        try{
            if(rs!=null)
            {
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (SQLException e){
            System.out.println(e);
        }
    }
}
